const Sequelize = require("sequelize");

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  "postgres://postgres:password@localhost:6432/postgres";

async function assigntask(config) {
  try {
    var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});

    //fetch team members
    let team_members = [];
    if (config.config.teams.length > 0) {
      var res = await sequelize.query(
        "select user_id from team_member where owner_id = :orgId and is_team = :isTeam and path in (:teams)",
        {
          replacements: {
            orgId: config.config.orgid,
            isTeam: false,
            teams: config.config.teams
          }
        }
      );
      team_members = res[0];
    }
    const users = new Set(config.config.members);
    team_members.map(member => users.add(member.user_id));
    const userArray = Array.from(users);
    if (userArray.length > 0) {
      let total = config.config.number;
      const numberPerUser = Math.ceil(total / userArray.length);
      for (let i = 0; i < userArray.length; i += 1) {
        const currentNumber = total > numberPerUser ? numberPerUser : total;
        var res = await sequelize.query(
          "update project_task_item set label_user = :user,state = :state WHERE id IN (SELECT id FROM project_task_item WHERE project_id = :projectId and label_user is null LIMIT :number)",
          {
            replacements: {
              number: currentNumber,
              projectId: config.project_id,
              user: userArray[i],
              state: "label"
            }
          }
        );
        console.log(`assign ${currentNumber} label task to ${userArray[i]}`);
        total = total - currentNumber;
      }
    }
    return res;
  } catch (e) {
    console.log(e);
    throw new Error(e);
  } finally {
    sequelize.close();
  }
}

module.exports.assigntask = assigntask;
